#include "stdafx.h"
#include "SimpleSocketTestSuite.h"

namespace CO { namespace SpiFoundation { namespace RoomFW {

SimpleSocketTestSuite::SimpleSocketTestSuite(void)
{
	TEST_ADD(SimpleSocketTestSuite::basic)
}

SimpleSocketTestSuite::~SimpleSocketTestSuite(void)
{
}

void SimpleSocketTestSuite::setup()
{
	// Initialize Winsock
	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (0 != iResult)
	{
		std::cout << "Error " << iResult << " at WSAStartup()" << std::endl;
	}
}

void SimpleSocketTestSuite::tear_down()
{
	// Shutdown Winsock
	int iResult = WSACleanup();
	if (SOCKET_ERROR == iResult)
	{
		std::cout << "Error " << WSAGetLastError() << " at WSAStartup()" << std::endl;
	}
}

void SimpleSocketTestSuite::basic(void)
{
	CO::SpiFoundation::RoomFW::SimpleSocket listener;
	CO::SpiFoundation::RoomFW::SimpleSocket client;

	// Check validity, use SOCKET cast to double check.
	TEST_ASSERT(!listener.valid());
	SOCKET sh = listener;
	TEST_ASSERT(INVALID_SOCKET == sh);

	TEST_ASSERT(!client.valid());
	sh = client;
	TEST_ASSERT(INVALID_SOCKET == sh);

	// Test basic functionality.
	const int port = 12727;
	const char* addr = "127.0.0.1";
	TEST_ASSERT(listener.listen(port, addr));
	TEST_ASSERT(client.connect(port, addr));
	CO::SpiFoundation::RoomFW::SimpleSocket::SocketPtr server = listener.accept();
	TEST_ASSERT(0 != server);
	const std::string msg("Hello Socket World");
	TEST_ASSERT(client.sendMessage(msg));
	std::string rcv;
	TEST_ASSERT(server->receiveMessage(rcv));
	TEST_ASSERT(msg == rcv);

	// Close and check validity, use SOCKET cast to double check.
	TEST_ASSERT(client.close());
	TEST_ASSERT(server->close());
	TEST_ASSERT(listener.close(false));

	TEST_ASSERT(!listener.valid());
	sh = listener;
	TEST_ASSERT(INVALID_SOCKET == sh);

	TEST_ASSERT(!client.valid());
	sh = client;
	TEST_ASSERT(INVALID_SOCKET == sh);

	TEST_ASSERT(!server->valid());
	sh = *server;
	TEST_ASSERT(INVALID_SOCKET == sh);
}

}}}
